package avicit.cbb.businessclass.fondsmanage.action;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import avicit.cbb.businessclass.fondsmanage.domain.DSConfigBean;
import avicit.cbb.businessclass.fondsmanage.service.ParseDSConfigService;
import avicit.platform6.core.spring.SpringFactory;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

/**
 * 数据库连接池管理类
 */
@SuppressWarnings({"rawtypes","deprecation"})
public class DBConnectionCustomManager {
	private static final Logger logger =  LoggerFactory.getLogger(DBConnectionCustomManager.class);
	private ParseDSConfigService parseDSConfigService = SpringFactory.getBean("parseDSConfigServiceImpl");

	static private DBConnectionCustomManager instance;// 唯一数据库连接池管理实例类
	
	private Vector drivers = new Vector();// 驱动信息
	private Hashtable pools = new Hashtable();// 连接池
	
	/**
	 * 实例化管理类
	 * @throws Exception 
	 */
	public DBConnectionCustomManager(String params) throws Exception {
		// TODO Auto-generated constructor stub
		this.init(params);
	}
	
	/**
	 * 得到唯一实例管理类
	 * @return
	 * @throws Exception 
	 */
	static synchronized public DBConnectionCustomManager getInstance(String params) throws Exception {
		if (instance == null) {
			instance = new DBConnectionCustomManager(params);
		}
		return instance;

	}
	
	/**
	 * 初始化连接池的参数
	 * @param params
	 * @throws Exception 
	 */
	private void init(String params) throws Exception {
		// 加载驱动程序
		this.loadDrivers(params);
		// 创建连接池
		Iterator alldriver = drivers.iterator();
		while (alldriver.hasNext()) {
			this.createPools((DSConfigBean) alldriver.next());
			logger.info("创建连接池...");
		}
		logger.info("创建连接池完毕...");
	}

	/**
	 * 加载驱动程序
	 * @param params
	 * @throws Exception 
	 */
	private void loadDrivers(String params) throws Exception {
		Map<String,Object> paramMap = new HashMap<String,Object>();
		if(params != null && !"".equals(params)){
			String [] strArray = params.split("_");
			if (strArray.length > 2) {
				paramMap.put("sysId", strArray[2]);
			} else {
				paramMap.put("sysId", strArray[1]);
			}
			
		}
		drivers = this.parseDSConfigService.getDsConfigInfo(paramMap);
		logger.info("加载驱动程序...");
	}
	
	/**
	 * 创建连接池
	 * @param props
	 */
	@SuppressWarnings("unchecked")
	private void createPools(DSConfigBean dsb) {
		try {
			Class.forName(dsb.getDriver());
			BoneCPConfig config = new BoneCPConfig();
			//连接池名
			config.setPoolName(dsb.getName());
			//数据库url
			config.setJdbcUrl(dsb.getUrl());
			//用户名
			config.setUsername(dsb.getUsername());
			//密码
			config.setPassword(dsb.getPassword());
			//连接池在每个分区中的最大连接数 
			config.setMaxConnectionsPerPartition(dsb.getMaxConnPer());
			//连接池在每个分区中的最小连接数
			config.setMinConnectionsPerPartition(dsb.getMinConnPer());
			//设置分区 
			config.setPartitionCount(dsb.getPartitionCount());
			//设置连接空闲时间(分钟)
			config.setIdleMaxAge(dsb.getIdleMaxAge());
			//当连接池中的连接耗尽时BoneCP一次同时获取的连接数 
			config.setAcquireIncrement(dsb.getAcquireIncrement());
			//设置连接池阀值
			config.setPoolAvailabilityThreshold(dsb.getPoolAvailabilityThreshold());
			//获取connection超时的时间
			config.setConnectionTimeout(dsb.getConnectionTimeout());
			//设置测试connection的间隔时间(分钟)
			config.setIdleConnectionTestPeriod(dsb.getIdleConnectionTestPeriod());
			BoneCP boneCp = new BoneCP(config);
			pools.put(dsb.getName(), boneCp);
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}

	/**
	 * 供全宗管理保存数据源时调用，重新构建连接池
	 * @param params
	 * @return
	 * @throws Exception 
	 */
	public void saveConnectionPool(String params) throws Exception {
		//清除驱动
		if (drivers != null){
			drivers.removeAllElements();//remove all
		}
		//关闭连接池
		if (pools != null){
			Iterator it = pools.keySet().iterator();
			while(it.hasNext()){
				String key = (String)it.next();
	        	BoneCP pool = (BoneCP) pools.get(key);// 根据关键名字得到连接池
	    		if (pool != null){
	    			pool.close();
	    			it.remove();
	    			logger.info("关闭连接池...");
	    		}  
	        }
		}
		instance = new DBConnectionCustomManager(params);//直接实例化类
	}
	
	/**
	 * 得到一个连接根据连接池的名字name
	 * @param params
	 * @return
	 */
	public Connection getConnection(String params) {
		String name = "";
		if(params != null && !"".equals(params)){
			String [] strArray = params.split("_");
			if (strArray.length > 2) {
				name = strArray[2];
			} else {
				name = strArray[1];
			}
		}
		BoneCP pool = null;
		Connection con = null;
		pool = (BoneCP) pools.get(name);// 从名字中获取连接池
		try {
			con = pool.getConnection();// 从选定的连接池中获得连接
			if (con != null){
//				System.out.println("得到连接。。。");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return con;
	}
	
	/**
	 * 释放连接
	 * @param params
	 * @param con
	 */
	public void deleteConnection(String params, Connection con) {
		String name = "";
		if(params != null && !"".equals(params)){
			String [] strArray = params.split("_");
			if (strArray.length > 2) {
				name = strArray[2];
			} else {
				name = strArray[1];
			}
		}
		BoneCP pool = (BoneCP) pools.get(name);// 根据关键名字得到连接池
		if (pool != null){
			if (con != null){
				try {
					con.close();//释放连接
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
